/**
 * 
 */
package com.angis.fx.activity.search;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.angis.fx.activity.R;
import com.angis.fx.activity.jcdj.DailyCheckResultActivity;
import com.angis.fx.activity.service.FieldSearchService;
import com.angis.fx.data.ChangsuoInformation;
import com.angis.fx.data.SearchCondition;
import com.angis.fx.util.DataParseUtil;

/**
 * @author Han
 * 
 */
public class BriefSearchResultActivity extends Activity {

	private ListView mListView;

	private List<ChangsuoInformation> mPlaceList;
	
	private List<HashMap<String, String>> mValueMapList;

	private int mLastPosition = -1;

	private View mLastView;

	private int mPageIndex = 1;

	private int mTotalCount;

	private Button mFirstPage;

	private Button mPreviousPage;

	private Button mNextPage;

	private Button mLastPage;
	private TextView pageShow;
	private SearchCondition mCondition;
	
	private UpdateReceiver receiver;
	
	private ProgressDialog mProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.briefsearchresult);
		
		initActivity();

		displayResults();
		
	}

	private void displayResults() {
		mProgress = ProgressDialog.show(BriefSearchResultActivity.this, "", "场所查询中...", true);
		receiver = new UpdateReceiver();
        IntentFilter filter = new IntentFilter();
         // find a action. com.hoperun.gpsService is defined in GpsService class
        filter.addAction("sendsearchresult");
        this.registerReceiver(receiver, filter);
        Intent intent = new Intent(BriefSearchResultActivity.this,FieldSearchService.class);  
        mCondition.setPageIndex(mPageIndex);
        intent.putExtra("searchcondition", mCondition);
        startService(intent); 
        
        
	}
	
	public class UpdateReceiver extends BroadcastReceiver{
	    
        @Override
        public void onReceive(Context context, Intent intent) {
        	mProgress.dismiss();
        	BriefSearchResultActivity.this.unregisterReceiver(receiver);
        	String response = intent.getStringExtra("results");
        	try{
        	if (response.equals("")){
        		mTotalCount = 0;
        		setButtonStyle();
        		return;
        	} else {
        		mTotalCount = Integer.parseInt(response.split("::")[1]);
        		if(mPageIndex==1 && mTotalCount!=0){
        			setPage(1);
        		}
        		response = response.split("::")[0];
            	if (response.indexOf("^") != -1	&& response.indexOf("=") != -1) {
        			mPlaceList = DataParseUtil.parseChangsuoInfo(DataParseUtil.handleResponse(response));
        		}else 
        			mPlaceList = new ArrayList<ChangsuoInformation>();
        		
    	    		mValueMapList = new ArrayList<HashMap<String, String>>();
    	    		HashMap<String, String> lInfoMap;
    	    		for (ChangsuoInformation lInfo : mPlaceList){
    	    			lInfoMap = new HashMap<String, String>();
    	    			lInfoMap.put("title", lInfo.getTitle());
    	    			lInfoMap.put("address", lInfo.getAddress());
    	    			lInfoMap.put("type", lInfo.getAreaType());
    	    			mValueMapList.add(lInfoMap);
        		}
        	}
    		
    		SimpleAdapter lAdapter = new SimpleAdapter(BriefSearchResultActivity.this, mValueMapList,
    				R.layout.briefsearchresultlayout, new String[] { "", "title",
    						"address", "type" }, new int[] { 0,
    						R.id.changsuonamedisplay, R.id.changsuoaddressdisplay,
    						R.id.changsuotypedisplay });
    		mListView.setAdapter(lAdapter);
    		mListView.setOnItemClickListener(new OnItemClickListener() {
    			@Override
    			public void onItemClick(AdapterView<?> pAdapterView, View pView,
    					int pSelectedIndex, long arg3) {
    				if (pSelectedIndex != mLastPosition) {
    					setVisible(pView);
    					setGone(mLastView);
    					mLastPosition = pSelectedIndex;
    					mLastView = pView;
    					Button lDetailsButton = (Button) pView
    							.findViewById(R.id.csdetailsbutton);
    					Button lCheckButton = (Button) pView
    							.findViewById(R.id.dailycheckbutton);
    					lDetailsButton.setOnClickListener(new OnClickListener() {

    						@Override
    						public void onClick(View v) {
    							Intent lIntent = new Intent();
//    							Bundle lBundle = new Bundle();
//    							lBundle.putSerializable("selectedcs", mPlaceList.get(mLastPosition));
    							lIntent.putExtra("selectedcs", mPlaceList.get(mLastPosition));
//    							lIntent.putExtra("bundle", lBundle);
    							lIntent.setClass(BriefSearchResultActivity.this,
    									ChangsuoDetailsTab.class);
    							BriefSearchResultActivity.this
    									.startActivity(lIntent);

    						}
    					});
    					lCheckButton.setOnClickListener(new OnClickListener() {

    						@Override
    						public void onClick(View v) {
    							Intent lIntent = new Intent();
    							lIntent.putExtra("selectedcs", (ChangsuoInformation)mPlaceList.get(mLastPosition));
    							lIntent.setClass(BriefSearchResultActivity.this,
    									DailyCheckResultActivity.class);
    							BriefSearchResultActivity.this
    									.startActivity(lIntent);
    						}
    					});

    				}
    			}
    		});
    		
    		setButtonStyle();
        	}catch (Exception e){
        		Toast.makeText(BriefSearchResultActivity.this, "解析数据出错!", Toast.LENGTH_LONG).show();
        	}
        }
        
	}

	private void setButtonStyle() {
		if (mTotalCount == 0) {
			setPageControlButtonGone();
			Toast.makeText(this, "没有符合该条件的记录", Toast.LENGTH_LONG).show();
		} else {
			setPageControlButtonVisible();
			if (mPageIndex == 1) {
				mFirstPage.setEnabled(false);
				mPreviousPage.setEnabled(false);
				if (mTotalCount <= 10) {
					mNextPage.setEnabled(false);
					mLastPage.setEnabled(false);
				}
			} else {
				mFirstPage.setEnabled(true);
				mPreviousPage.setEnabled(true);
				if (mTotalCount % 10 == 0) {
					if (mPageIndex < mTotalCount / 10) {
						mNextPage.setEnabled(true);
						mLastPage.setEnabled(true);
					} else {
						mNextPage.setEnabled(false);
						mLastPage.setEnabled(false);
					}
				} else {
					if (mPageIndex < mTotalCount / 10 + 1) {
						mNextPage.setEnabled(true);
						mLastPage.setEnabled(true);
					} else {
						mNextPage.setEnabled(false);
						mLastPage.setEnabled(false);
					}
				}
			}

		}
	}

	private void initActivity() {

		mCondition = (SearchCondition) getIntent().getExtras().get(
				"searchcondition");
		mListView = (ListView) findViewById(R.id.briefSearchResult);

		mFirstPage = (Button) findViewById(R.id.firstpage);
		mPreviousPage = (Button) findViewById(R.id.previouspage);
		mNextPage = (Button) findViewById(R.id.nextpage);
		mLastPage = (Button) findViewById(R.id.lastpage);
		pageShow=(TextView) findViewById(R.id.briefpageshow);
		mFirstPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPageIndex = 1;
				setPage(mPageIndex);
				displayResults();
				setButtonStyle();
			}
		});

		mPreviousPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPageIndex = mPageIndex - 1;
				setPage(mPageIndex);
				displayResults();
				setButtonStyle();
			}
		});

		mNextPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPageIndex = mPageIndex + 1;	
				setPage(mPageIndex);
				displayResults();
				setButtonStyle();
			}
		});

		mLastPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPageIndex = (mTotalCount%10 == 0)? mTotalCount/10:mTotalCount/10+1;
				setPage(mPageIndex);
				displayResults();
				setButtonStyle();
			}
		});
	}

	/*
	 */
	private void setVisible(View view) {
		if (view == null)
			return;
		LinearLayout layout = (LinearLayout) view;
		layout.findViewById(R.id.changsuoaddressdisplay).setVisibility(
				View.VISIBLE);
		layout.findViewById(R.id.changsuotypedisplay).setVisibility(
				View.VISIBLE);
		layout.findViewById(R.id.buttonlayout).setVisibility(View.VISIBLE);
	}

	/*
	 */
	private void setGone(View view) {
		if (view == null)
			return;
		LinearLayout layout = (LinearLayout) view;
		layout.findViewById(R.id.changsuoaddressdisplay).setVisibility(
				View.GONE);
		layout.findViewById(R.id.changsuotypedisplay).setVisibility(View.GONE);
		layout.findViewById(R.id.buttonlayout).setVisibility(View.GONE);
	}

	private void setPageControlButtonGone() {
		mFirstPage.setVisibility(View.GONE);
		mPreviousPage.setVisibility(View.GONE);
		mNextPage.setVisibility(View.GONE);
		mLastPage.setVisibility(View.GONE);
	}

	private void setPageControlButtonVisible() {
		mFirstPage.setVisibility(View.VISIBLE);
		mPreviousPage.setVisibility(View.VISIBLE);
		mNextPage.setVisibility(View.VISIBLE);
		mLastPage.setVisibility(View.VISIBLE);
	}
	private void setPage(int page){
		int total = (mTotalCount%10 == 0)? mTotalCount/10:mTotalCount/10+1;
		pageShow.setText(page+"/"+total);
	}
}
